namespace SubhadraSolutions.Sharp.Logging.LogSubscribers.FileSystem
{
    using SubhadraSolutions.Sharp.Utils.Data;
    using SubhadraSolutions.Sharp.Utils.Xml;
    using System.IO;
    using System.Security;
    using System.Xml;

    public class XmlFileLogSubscriber : AbstractStructuredFileLogSubscriber
    {
        #region Fields

        private string[,] _columnNames;

        #endregion Fields

        #region Constructors

        public XmlFileLogSubscriber()
        {
            fileEndingString = "</LogItems>";
        }

        #endregion Constructors

        #region Methods

        protected override void writeFileHeader(StreamWriter writer,
            DataReaderDataTableAdapter adapter)
        {
            writer.Write("<?xml version=\"1.0\"?>\r\n<LogItems>\r\n");
            if (_columnNames == null)
            {
                _columnNames = new string[adapter.ColumnCount, 2];
                for (int i = 0; i < adapter.ColumnCount; i++)
                {
                    string columnName = adapter.GetColumnName(i);
                    columnName = XmlConvert.EncodeName(columnName);
                    _columnNames[i, 0] = "<" + columnName + ">";
                    _columnNames[i, 1] = "</" + columnName + ">";
                }
            }
        }

        protected override void writeRows(StreamWriter writer, DataReaderDataTableAdapter adapter)
        {
            while (adapter.Read())
            {
                writer.Write("\t<Item>\r\n");
                for (int i = 0; i < adapter.ColumnCount; i++)
                {
                    writer.Write("\t\t");
                    writer.Write(_columnNames[i, 0]);
                    object o = adapter.GetValue(i);
                    if (o != null)
                    {
                        var xmlExportable = o as IXmlExportable;
                        if (xmlExportable != null)
                        {
                            writer.Write("\r\n");
                            xmlExportable.WriteXml(writer, "\t\t\t");
                            writer.Write("\t\t");
                        }
                        else
                        {
                            string s = o.ToString();
                            s = SecurityElement.Escape(s);
                            writer.Write(s);
                        }
                    }
                    writer.Write(_columnNames[i, 1]);
                    writer.Write("\r\n");
                }
                writer.Write("\t</Item>\r\n");
            }
        }

        #endregion Methods
    }
}